package com.xiaoliu.servlet;

import com.xiaoliu.dao.EnrollDao;
import com.xiaoliu.dao.impl.UserDaoImpl;
import com.xiaoliu.util.RegexUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/enroll")
public class Enroll extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String user = req.getParameter("userName");
        String pwd = req.getParameter("pwd");
        String email = req.getParameter("email");
        String sex = req.getParameter("sex");

        // 响应的编码
        resp.setCharacterEncoding("UTF-8");
        // 文本格式
        resp.setContentType("text/html;charset=UTF-8");
        UserDaoImpl userDao = new UserDaoImpl();
        boolean exists;// 数据库是否存在某个用户
        boolean register;// 数据是否添加成功
        boolean bo = RegexUtil.isValidEmail(email);// 判断邮箱格式
        if (bo) {// 邮箱格式正确 执行下面操作
            exists = userDao.userExists(user);
            register = userDao.register(user, pwd, email, sex);
            if (exists) {
                resp.sendRedirect("userExists.jsp");
            } else if (register) {
                resp.sendRedirect("index.jsp");
            } else {
                resp.sendRedirect("cao.jsp");
            }
        } else {
            resp.sendRedirect("illegalEmail.jsp");
        }

    }

}